import json
import requests
from bs4 import BeautifulSoup
import time
import re

# 默认数据
proxies = { "http": None, "https": None}
cookies = 'lang=cn; 2Moons=91nvj1blt1nhsolodelefdu8vm'
url = 'https://nstar.zsuuu.com'

# 这里放母星
mainPlanet = '1:22:15'
mainPlanetId = 444
# 这里放其他星
planetMap = {
    '1:22:12':445,
}
# 目前不支持卫星

def upgradeBuilding(planet, buildingId, level=None):
    sleepCnt = 0
    while True:
        planetId = planetMap.get(planet)
        resp = requests.get(url + '/game.php?page=buildings&cp=' + str(planetId), headers={ 'cookie': cookies }, proxies=proxies)
        soup = BeautifulSoup(resp.text, 'html.parser')
        buildDiv = soup.find('div', id='build_' + str(buildingId))
        pricesDiv = buildDiv.find('div', 'prices')
        necccos = pricesDiv.find('div', 'necccos')
        buildtitle = buildDiv.find('div', 'head').get_text().replace('\n','').replace(' ','')
        if necccos:
            print(planet, planetId, buildingId, necccos.string)
            return
        disableUpgade = buildDiv.find('span', 'btn_build red')
        if disableUpgade:
            print(planet, planetId, buildingId, '资源不足', buildtitle, disableUpgade.get_text(), disableUpgade.get_text().replace(' ', '') == '建设到下一级')
            if buildtitle.find('等级' + str(level)) > 0: return
            time.sleep(1)
            sleepCnt += 1
            if sleepCnt < 3: continue
            # if disableUpgade.get_text().replace(' ', '') == '建设到下一级':
            #     continue
            return
        sleepCnt = 0
        nextLevelInput = buildDiv.find('input', id='b_input_' + str(buildingId))
        if nextLevelInput:
            nextLevel = int(nextLevelInput['value'])
            if level and level < nextLevel:
                print(planet, planetId, buildingId, '等级已满足', nextLevel - 1)
                return
            # https://nstar.zsuuu.com/game.php?page=buildings
            params = {'cmd': 'insert','building': buildingId,'lvlup1': '0','levelToBuildInFo': '0','lvlup': '1'}
            resp = requests.post(url + '/game.php?page=buildings', data=params, headers={ 'cookie': cookies }, proxies=proxies, allow_redirects=False)
            print(planet, planetId, buildingId, '升级', nextLevel, resp)
            if level and level == nextLevel:
                print(planet, planetId, buildingId, '等级已满足', nextLevel)
                break
            time.sleep(0.3)
        else:
            print(planet, planetId, buildingId, '无等级信息')
            return

def transferResources(planet, toPlanet, resource={}):
    # https://nstar.zsuuu.com/game.php?page=fleetStep1&cp={{cp}}
    toPlanetPiece = toPlanet.split(':')
    planetId = planetMap.get(planet)
    if planet == mainPlanet: planetId = mainPlanetId
    planetPiece = planet.split(':')
    params = {
        'galaxy':planetPiece[0],
        'system':planetPiece[1],
        'planet':planetPiece[2],
        'type':1,
        'target_mission':0,
        'ship219':100,
        'save_groop':''
    }
    if planet == mainPlanet: params['ship219'] = 200
    resp = requests.post(url + '/game.php?page=fleetStep1&cp=' + str(planetId), data=params, headers={ 'cookie': cookies }, proxies=proxies, allow_redirects=False)
    soup = BeautifulSoup(resp.text, 'html.parser')
    tokenInput = soup.find('input', attrs={'name':'token'})
    if not tokenInput:
        print(planet, '无可用搬运船')
        return
    token = tokenInput['value']
    current_metal_ele = soup.find('span', id='current_metal')
    current_metal = int(float(current_metal_ele['data-real']))
    current_crystal_ele = soup.find('span', id='current_crystal')
    current_crystal = int(float(current_crystal_ele['data-real']))
    current_deuterium_ele = soup.find('span', id='current_deuterium')
    current_deuterium = int(float(current_deuterium_ele['data-real']))
    # https://nstar.zsuuu.com/game.php?page=fleetStep2
    params = {
        'token':token,
        'fleet_group':0,
        'target_mission':0,
        'galaxy':toPlanetPiece[0],
        'system':toPlanetPiece[1],
        'planet':toPlanetPiece[2],
        'type':1,
        'speed':10,
        'shortcut[][name]':'',
        'shortcut[][galaxy]':'',
        'shortcut[][system]':'',
        'shortcut[][planet]':'',
        'shortcut[][type]':1
    }
    resp = requests.post(url + '/game.php?page=fleetStep2', data=params, headers={ 'cookie': cookies }, proxies=proxies, allow_redirects=False)
    # https://nstar.zsuuu.com/game.php?page=fleetStep3
    total = 260000000000
    if current_metal > total:
        current_metal = total
        total = 0
    else: total -= current_metal
    if current_crystal > total:
        current_crystal = total
        total = 0
    else: total -= current_crystal
    if current_deuterium > total:
        current_deuterium = total
        total = 0
    else: total -= current_deuterium
    params = {
        'token':token,
        'mission':3,
        'metal':resource.get('metal', current_metal),
        'crystal':resource.get('crystal', current_crystal),
        'deuterium':resource.get('deuterium', current_deuterium),
    }
    resp = requests.post(url + '/game.php?page=fleetStep3', data=params, headers={ 'cookie': cookies }, proxies=proxies, allow_redirects=False)
    soup = BeautifulSoup(resp.text, 'html.parser')
    result = soup.find('div', 'ally_contents')
    if result: result = result.string
    print(planet, '=>', toPlanet, result)

def checkResources(planet, planetId):
    resp = requests.get(url + '/game.php?page=shipyard&mode=fleet&cp=' + str(planetId), headers={ 'cookie': cookies }, proxies=proxies)
    soup = BeautifulSoup(resp.text, 'html.parser')
    defendDiv = soup.find('div', id='s_217')
    remainEle = defendDiv.find('span', id='val_217')
    remain = 0
    if remainEle.string:
        remain = int(re.split('\(|\)|\s', str(remainEle.string))[2].replace('.','').replace(',',''))
    print(planet, '217', remain)
    
    current_metal_ele = soup.find('span', id='current_metal')
    current_metal = int(float(current_metal_ele['data-real']))
    current_crystal_ele = soup.find('span', id='current_crystal')
    current_crystal = int(float(current_crystal_ele['data-real']))
    current_deuterium_ele = soup.find('span', id='current_deuterium')
    current_deuterium = int(float(current_deuterium_ele['data-real']))

    print(current_metal, current_crystal, current_deuterium)

def getPlanetId(num=None):
    resp = requests.get(url + '/game.php?page=control', headers={ 'cookie': cookies }, proxies=proxies, allow_redirects=False)
    soup = BeautifulSoup(resp.text, 'html.parser')
    options = soup.find('select', id='lstPlaneta').find_all('option')
    if num: options = options[-num:]
    for opt in options:
        id = int(opt['value'].split('cp=')[1])
        planet = opt.string.split('[')[1].split(']')[0]
        print("    '%s': %d," % (planet, id))
        space = int(soup.find('a', string='[%s]'%planet).parent.find_next_sibling('div', 'imper_block_info_text').string.split(' / ')[1])
        if space < 135: print('    # %s space: %d' % (planet, space))

def sendShip(planet, toPlanet, shipData):
    # https://nstar.zsuuu.com/game.php?page=fleetStep1&cp={{cp}}
    toPlanetPiece = toPlanet.split(':')
    planetId = planetMap.get(planet)
    if not planetId: planetId = mainPlanetId
    planetPiece = planet.split(':')
    params = {
        'galaxy':planetPiece[0],
        'system':planetPiece[1],
        'planet':planetPiece[2],
        'type':1,
        'target_mission':0,
        'save_groop':''
    }
    for shipId in shipData.keys():
        params[shipId] = shipData[shipId]
    resp = requests.post(url + '/game.php?page=fleetStep1&cp=' + str(planetId), data=params, headers={ 'cookie': cookies }, proxies=proxies, allow_redirects=False)
    soup = BeautifulSoup(resp.text, 'html.parser')
    tokenInput = soup.find('input', attrs={'name':'token'})
    if not tokenInput:
        print(planet, '无可用搬运船')
        return
    token = tokenInput['value']
    # https://nstar.zsuuu.com/game.php?page=fleetStep2
    params = {
        'token':token,
        'fleet_group':0,
        'target_mission':0,
        'galaxy':toPlanetPiece[0],
        'system':toPlanetPiece[1],
        'planet':toPlanetPiece[2],
        'type':1,
        'speed':10,
        'shortcut[][name]':'',
        'shortcut[][galaxy]':'',
        'shortcut[][system]':'',
        'shortcut[][planet]':'',
        'shortcut[][type]':1
    }
    resp = requests.post(url + '/game.php?page=fleetStep2', data=params, headers={ 'cookie': cookies }, proxies=proxies, allow_redirects=False)
    # https://nstar.zsuuu.com/game.php?page=fleetStep3
    params = {
        'token':token,
        'mission':4,
        'metal':0,
        'crystal':0,
        'deuterium':0,
    }
    resp = requests.post(url + '/game.php?page=fleetStep3', data=params, headers={ 'cookie': cookies }, proxies=proxies, allow_redirects=False)
    soup = BeautifulSoup(resp.text, 'html.parser')
    result = soup.find('div', 'ally_contents')
    if result: result = result.string
    print(planet, '=>', toPlanet, result)

def checkDefend(planetId, defendId, minRemain):
    # https://nstar.zsuuu.com/game.php?page=shipyard&mode=defense&cp=19
    resp = requests.get(url + '/game.php?page=shipyard&mode=defense&cp=' + str(planetId), headers={ 'cookie': cookies }, proxies=proxies)
    soup = BeautifulSoup(resp.text, 'html.parser')
    defendDiv = soup.find('div', id='s_' + str(defendId))
    remainEle = defendDiv.find('span', id='val_' + str(defendId))
    remain = 0
    if remainEle.string:
        remain = int(re.split('\(|\)|\s', str(remainEle.string))[2].replace('.','').replace(',',''))
    print(defendId, '防御剩余', remain)
    if remain < minRemain:
        need = minRemain - remain
        if need > 100000000: need = 100000000
        # https://nstar.zsuuu.com/game.php?page=shipyard&mode=defense
        params = { 'fmenge[' + str(defendId) + ']': need }
        resp = requests.post(url + '/game.php?page=shipyard&mode=defense', data=params, headers={ 'cookie': cookies }, proxies=proxies, allow_redirects=False)
        print(defendId, '防御补充', need, resp)

def checkShip(planetId, shipId, minRemain):
    # https://nstar.zsuuu.com/game.php?page=shipyard&mode=defense&cp=19
    resp = requests.get(url + '/game.php?page=shipyard&mode=fleet&cp=' + str(planetId), headers={ 'cookie': cookies }, proxies=proxies)
    soup = BeautifulSoup(resp.text, 'html.parser')
    defendDiv = soup.find('div', id='s_' + str(shipId))
    remainEle = defendDiv.find('span', id='val_' + str(shipId))
    remain = 0
    if remainEle.string:
        remain = int(re.split('\(|\)|\s', str(remainEle.string))[2].replace('.','').replace(',',''))
    print(shipId, '飞船剩余', remain)
    if remain < minRemain:
        need = minRemain - remain
        if need > 100000000: need = 100000000
        # https://nstar.zsuuu.com/game.php?page=shipyard&mode=fleet
        params = { 'fmenge[' + str(shipId) + ']': need }
        resp = requests.post(url + '/game.php?page=shipyard&mode=fleet', data=params, headers={ 'cookie': cookies }, proxies=proxies, allow_redirects=False)
        print(shipId, '飞船补充', need, resp)
        time.sleep(1)

def checkShips(planetId, shipData):
    needAddShip = {}
    resp = requests.get(url + '/game.php?page=shipyard&mode=fleet&cp=' + str(planetId), headers={ 'cookie': cookies }, proxies=proxies)
    soup = BeautifulSoup(resp.text, 'html.parser')
    for shipId in shipData.keys():
        defendDiv = soup.find('div', id='s_' + str(shipId))
        remainEle = defendDiv.find('span', id='val_' + str(shipId))
        remain = 0
        if remainEle.string:
            remain = int(re.split('\(|\)|\s', str(remainEle.string))[2].replace('.','').replace(',',''))
        print(shipId, '飞船剩余', remain)
        if remain < shipData[shipId]:
            needAddShip[shipId] = shipData[shipId]
    return needAddShip

def explore(planet, planetId, shipData, maxExplore):
    # https://nstar.zsuuu.com/game.php?page=fleetTable&cp=19
    resp = requests.get(url + '/game.php?page=fleetTable&cp=' + str(planetId), headers={ 'cookie': cookies }, proxies=proxies)
    soup = BeautifulSoup(resp.text, 'html.parser')
    exploreEle = soup.find('div', 'gray_flettab').find('span')
    currExplore = int(exploreEle.string[0])
    if currExplore >= maxExplore: return
    print('当前探索数量', currExplore)

    # https://nstar.zsuuu.com/game.php?page=fleetStep1&cp={{cp}}
    planetPiece = planet.split(':')
    params = {
        'galaxy':planetPiece[0],
        'system':planetPiece[1],
        'planet':16,
        'type':1,
        'target_mission':15,
        'save_groop':''
    }
    for shipId in shipData.keys():
        params[shipId] = shipData[shipId]
    resp = requests.post(url + '/game.php?page=fleetStep1&cp=' + str(planetId), data=params, headers={ 'cookie': cookies }, proxies=proxies, allow_redirects=False)
    soup = BeautifulSoup(resp.text, 'html.parser')
    tokenInput = soup.find('input', attrs={'name':'token'})
    if not tokenInput:
        print(planet, '无可用探索船')
        return
    token = tokenInput['value']
    # https://nstar.zsuuu.com/game.php?page=fleetStep2
    params = {
        'token':token,
        'fleet_group':0,
        'target_mission':15,
        'galaxy':planetPiece[0],
        'system':planetPiece[1],
        'planet':16,
        'type':1,
        'speed':10,
        'shortcut[][name]':'',
        'shortcut[][galaxy]':'',
        'shortcut[][system]':'',
        'shortcut[][planet]':'',
        'shortcut[][type]':1
    }
    resp = requests.post(url + '/game.php?page=fleetStep2', data=params, headers={ 'cookie': cookies }, proxies=proxies, allow_redirects=False)
    # https://nstar.zsuuu.com/game.php?page=fleetStep3
    params = {
        'token':token,
        'mission':15,
        'metal':0,
        'crystal':0,
        'deuterium':0,
        'staytime': 1
    }
    resp = requests.post(url + '/game.php?page=fleetStep3', data=params, headers={ 'cookie': cookies }, proxies=proxies, allow_redirects=False)
    soup = BeautifulSoup(resp.text, 'html.parser')
    result = soup.find('div', 'ally_contents')
    if result: result = result.string
    print(planet, '探索', result)

def sendNuke(planet, toPlanet, nukeNum):
    checkDefend(planetMap[planet], 503, 900)
    time.sleep(1)
    # https://nstar.zsuuu.com/game.php?page=fleetMissile
    toPlanetPiece = toPlanet.split(':')
    params = {
        'galaxy': toPlanetPiece[0],
        'system': toPlanetPiece[1],
        'planet': toPlanetPiece[2],
        'type': 1,
        'SendMI': nukeNum,
        'Target': 0
    }
    resp = requests.post(url + '/game.php?page=fleetMissile&cp=' + str(planetMap[planet]), data=params, headers={ 'cookie': cookies }, proxies=proxies, allow_redirects=False)
    soup = BeautifulSoup(resp.text, 'html.parser')
    result = soup.find('div', 'ally_contents')
    if result: result = result.get_text()
    print('发送核弹', planet, '=>', toPlanet, result)

def addNewPlanet(planet, planetId, newPlanet):
    # https://nstar.zsuuu.com/game.php?page=fleetStep1&cp={{cp}}
    toPlanetPiece = newPlanet.split(':')
    planetPiece = planet.split(':')
    params = {
        'galaxy':planetPiece[0],
        'system':planetPiece[1],
        'planet':planetPiece[2],
        'type':1,
        'target_mission':0,
        'ship217':10,
        'ship208':1,
        'save_groop':''
    }
    resp = requests.post(url + '/game.php?page=fleetStep1&cp=' + str(planetId), data=params, headers={ 'cookie': cookies }, proxies=proxies, allow_redirects=False)
    soup = BeautifulSoup(resp.text, 'html.parser')
    tokenInput = soup.find('input', attrs={'name':'token'})
    if not tokenInput:
        print(planet, '无可用搬运船')
        return
    token = tokenInput['value']
    # https://nstar.zsuuu.com/game.php?page=fleetStep2
    params = {
        'token':token,
        'fleet_group':0,
        'target_mission':0,
        'galaxy':toPlanetPiece[0],
        'system':toPlanetPiece[1],
        'planet':toPlanetPiece[2],
        'type':1,
        'speed':10,
        'shortcut[][name]':'',
        'shortcut[][galaxy]':'',
        'shortcut[][system]':'',
        'shortcut[][planet]':'',
        'shortcut[][type]':1
    }
    resp = requests.post(url + '/game.php?page=fleetStep2', data=params, headers={ 'cookie': cookies }, proxies=proxies, allow_redirects=False)
    # https://nstar.zsuuu.com/game.php?page=fleetStep3
    params = {
        'token':token,
        'mission':7,
        'metal':1000000000,
        'crystal':1000000000,
        'deuterium':1000000000,
    }
    resp = requests.post(url + '/game.php?page=fleetStep3', data=params, headers={ 'cookie': cookies }, proxies=proxies, allow_redirects=False)
    soup = BeautifulSoup(resp.text, 'html.parser')
    result = soup.find('div', 'ally_contents')
    if result: result = result.string
    print(planet, '=>', newPlanet, result)
    pass

def needAttack(planetId):
    # https://nstar.zsuuu.com/game.php?page=fleetTable&cp={{cp}}
    resp = requests.get(url + '/game.php?page=fleetTable&cp=' + str(planetId), headers={ 'cookie': cookies }, proxies=proxies)
    soup = BeautifulSoup(resp.text, 'html.parser')
    total = int(soup.find('div', 'gray_flettab').get_text().split('舰队 ')[1].split(' / ')[0])
    exploreEle = soup.find('div', 'gray_flettab').find('span')
    currExplore = int(exploreEle.string[0])
    # print('当前', currExplore, '/', total)
    if total - currExplore > 0:
        return False
    return True

def attack(planet, planetId, toPlanet, shipData=None, sub=1):
    # https://nstar.zsuuu.com/game.php?page=fleetTable&cp={{cp}}
    resp = requests.get(url + '/game.php?page=fleetTable&cp=' + str(planetId), headers={ 'cookie': cookies }, proxies=proxies)
    soup = BeautifulSoup(resp.text, 'html.parser')
    total = int(soup.find('div', 'gray_flettab').get_text().split('舰队 ')[1].split(' / ')[0])
    exploreEle = soup.find('div', 'gray_flettab').find('span')
    currExplore = int(exploreEle.string[0])
    print('当前探索数量', currExplore, '/', total)
    if total - currExplore > 0:
        print('等待下次进攻', toPlanet)
        return False
    if shipData is None:
        shipData = {}
        shipListEle = soup.find_all('div', 'gray_ship2')[1].find_previous_siblings('div', 'build_box flethan')
        for shipEle in shipListEle:
            # name = shipEle.find('div', 'hang3').find('span').string
            num = shipEle.find('div', 'hang4').string.replace('.','').replace(',','')
            shipId = shipEle.find('div', 'hang4')['id'].split('_')[0]
            shipData[shipId] = int(int(num) / sub)
        shipData['ship219'] = 100
        if shipData.get('ship216', 0) > 0: shipData['ship216'] -= 5 * 10
        if shipData.get('ship227', 0) > 0: shipData['ship227'] -= 11 * 10
        if shipData.get('ship219', 0) > 0: shipData['ship219'] -= 20 * 10
    # https://nstar.zsuuu.com/game.php?page=fleetStep1&cp={{cp}}
    toPlanetPiece = toPlanet.split(':')
    planetId = planetMap.get(planet)
    planetPiece = planet.split(':')
    params = {
        'galaxy':planetPiece[0],
        'system':planetPiece[1],
        'planet':planetPiece[2],
        'type':1,
        'target_mission':1,
        'save_groop':''
    }
    for shipId in shipData.keys():
        params[shipId] = shipData[shipId]
    resp = requests.post(url + '/game.php?page=fleetStep1&cp=' + str(planetId), data=params, headers={ 'cookie': cookies }, proxies=proxies, allow_redirects=False)
    soup = BeautifulSoup(resp.text, 'html.parser')
    tokenInput = soup.find('input', attrs={'name':'token'})
    if not tokenInput:
        print(planet, '无可用搬运船')
        return
    token = tokenInput['value']
    # https://nstar.zsuuu.com/game.php?page=fleetStep2
    params = {
        'token':token,
        'fleet_group':0,
        'target_mission':1,
        'galaxy':toPlanetPiece[0],
        'system':toPlanetPiece[1],
        'planet':toPlanetPiece[2],
        'type':1,
        'speed':10,
        'shortcut[][name]':'',
        'shortcut[][galaxy]':'',
        'shortcut[][system]':'',
        'shortcut[][planet]':'',
        'shortcut[][type]':1
    }
    resp = requests.post(url + '/game.php?page=fleetStep2', data=params, headers={ 'cookie': cookies }, proxies=proxies, allow_redirects=False)
    # https://nstar.zsuuu.com/game.php?page=fleetStep3
    params = {
        'token':token,
        'mission':1,
        'metal':0,
        'crystal':0,
        'deuterium':0,
        'staytime':1,
    }
    resp = requests.post(url + '/game.php?page=fleetStep3', data=params, headers={ 'cookie': cookies }, proxies=proxies, allow_redirects=False)
    soup = BeautifulSoup(resp.text, 'html.parser')
    result = soup.find('div', 'ally_contents')
    if result: result = result.string
    print(planet, '进攻', toPlanet, result)
    # print(resp.text)
    return True

def claim(planet, planetId, toPlanet):
    # https://nstar.zsuuu.com/game.php?page=fleetStep1&cp={{cp}}
    toPlanetPiece = toPlanet.split(':')
    if not planetId: planetId = planetMap.get(planet)
    planetPiece = planet.split(':')
    params = {
        'galaxy':planetPiece[0],
        'system':planetPiece[1],
        'planet':planetPiece[2],
        'type':1,
        'target_mission':0,
        'ship219': 300,
        'ship208': 10,
        'save_groop':''
    }
    resp = requests.post(url + '/game.php?page=fleetStep1&cp=' + str(planetId), data=params, headers={ 'cookie': cookies }, proxies=proxies, allow_redirects=False)
    soup = BeautifulSoup(resp.text, 'html.parser')
    tokenInput = soup.find('input', attrs={'name':'token'})
    if not tokenInput:
        print(planet, '无可用搬运船')
        return
    token = tokenInput['value']
    # https://nstar.zsuuu.com/game.php?page=fleetStep2
    params = {
        'token':token,
        'fleet_group':0,
        'target_mission':0,
        'galaxy':toPlanetPiece[0],
        'system':toPlanetPiece[1],
        'planet':toPlanetPiece[2],
        'type':1,
        'speed':10,
        'shortcut[][name]':'',
        'shortcut[][galaxy]':'',
        'shortcut[][system]':'',
        'shortcut[][planet]':'',
        'shortcut[][type]':1
    }
    resp = requests.post(url + '/game.php?page=fleetStep2', data=params, headers={ 'cookie': cookies }, proxies=proxies, allow_redirects=False)
    # https://nstar.zsuuu.com/game.php?page=fleetStep3
    params = {
        'token':token,
        'mission':7,
        'metal':20000000000,
        'crystal':20000000000,
        'deuterium':20000000000,
    }
    resp = requests.post(url + '/game.php?page=fleetStep3', data=params, headers={ 'cookie': cookies }, proxies=proxies, allow_redirects=False)
    soup = BeautifulSoup(resp.text, 'html.parser')
    result = soup.find('div', 'ally_contents')
    if result: result = result.string
    print(planet, '占领', toPlanet, result)

def checkVM(planet):
    planetPiece = planet.split(':')
    params = {
        'galaxy':planetPiece[0],
        'system':planetPiece[1],
    }
    resp = requests.post(url + '/game.php?page=galaxy', data=params, headers={ 'cookie': cookies }, proxies=proxies, allow_redirects=False, timeout=5)
    soup = BeautifulSoup(resp.text, 'html.parser')
    line = soup.find_all('div', 'gal_number')[int(planetPiece[2])-1].parent
    # print(line)
    return line.find('span', string='VM') is not None

def searchAllPlayer(maxGalaxy, maxSystem):
    userMap = {}
    for galaxy in range(1, maxGalaxy + 1):
        for system in range(1, maxSystem + 1):
            # https://nstar.zsuuu.com/game.php?page=galaxy
            params = {
                'galaxy': galaxy,
                'system': system
            }
            resp = requests.post(url + '/game.php?page=galaxy', data=params, headers={ 'cookie': cookies }, proxies=proxies, allow_redirects=False)
            soup = BeautifulSoup(resp.text, 'html.parser')
            imgEles = soup.find_all('span', 'tooltip gal_img_planet')
            for imgEle in imgEles:
                planetName = imgEle['data-tooltip-content']
                username = imgEle.parent.find('span', 'galaxy-username').string
                print(username, planetName)
                planetList = userMap.get(username, [])
                planetList.append(planetName)
                userMap[username] = planetList
    print('=' * 80)
    for username in userMap.keys():
        print(username)
        showPlanets = []
        for planet in userMap[username]:
            print('\t', planet)
            showPlanets.append(re.split('\[|\]', planet)[1])
        print('\t\t', json.dumps(showPlanets))
        with open('G:/screeps/searchAllPlayer', 'a') as f:
            f.write(username + ' = ' + json.dumps(showPlanets) + '\n')

# 地图查找
# searchAllPlayer(9, 400)
# sys.exit(0)
整合 = [
    "1:44:15",

]

# 造船
# 幻影 ship252 40
# 猎户座 ship251 40
# 台风 ship250 40
# 泰坦 ship249 40
# 护卫级 ship227 10000
# 黑月 ship216 20000
# 战争要塞 ship214 2000
# 驱逐级 ship226 20000
# 黑色流浪者 ship228 10000
# 加利拉斯 ship247 10000
# 后卫 ship245 100000
# 星际战舰 ship213 2000000
# 战列巡洋舰 ship215 500000
# 战列舰 ship207 150000
# 巡洋舰 ship206 600000

# 轻型战机 ship204 100000000
# 军用运输机 ship217 600
# 太阳能卫星 ship212 1000000000


def autoAddShip(mainPlanetId):
    print('autoAddShip', mainPlanetId)
    needAddShip = checkShips(mainPlanetId, {
        '204':100000000000000000000,
        '212':1000000000
    })
    for shipId in needAddShip.keys():
        checkShip(mainPlanetId, shipId, needAddShip[shipId])

# 自动攻击
attackTarget = 整合 # [i for i in Fredrick_LX if i[0] == '4']
attackIndex = 1
def readAttackIndex():
    global attackIndex
    if attackIndex is None:
        with open('D:/screeps/attackIndex', 'r') as f:
            attackIndex = int(f.readline())
    return attackIndex

def writeAttackIndex():
    # 使用with语句打开文件，确保文件在使用完毕后自动关闭
    with open('D:/screeps/attackIndex', 'w') as f:
        # 将attackIndex变量的值转换为字符串并写入文件
            f.write(str(attackIndex))

def autoAttack(attackPlanet, attackPlanetId, check=False):
    # 读取攻击索引
    # readAttackIndex()
    global attackIndex  # 声明全局变量 attackIndex
    attackTargets = attackTarget.copy()  # 复制攻击目标列表
    if not checkVM(attackPlanet):  # 检查是否为 VM 模式
        print(attackPlanet,'非 VM 模式 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        attackTargets = attackTargets.copy()  # 如果不是 VM 模式，使用迷迭香的目标列表
    else:
        print(attackPlanet,'VM 模式')
    # targetPlanet = attackTargets[attackIndex % len(attackTargets)]  # 获取当前攻击目标
    targetPlanet = attackTargets[0]
    print('攻击目标', attackIndex, targetPlanet)
    toPlanetPiece = targetPlanet.split(':')  # 分割目标星球坐标
    shipData = None  # 初始化飞船数据为 None
    # main
    if int(targetPlanet[0]) > 1:# or (toPlanetPiece[0] == '1' and int(toPlanetPiece[1]) > 50):
        shipData = {
            'ship215': 10000,
            'ship219': 100,
            'ship228': 200
        }
        if targetPlanet == '5:19:7':
            shipData['ship215'] = 100000
        if targetPlanet == '9:19:7':
            shipData['ship215'] = 100000
        if int(targetPlanet.split(':')[1]) > 300:
            shipData['ship215'] = 100000
        if targetPlanet == '9:391:7':
            shipData = None
        if targetPlanet == '7:77:7':
            shipData = None
        if targetPlanet == '8:11:7':
            shipData = None
    # 9:399:12
    # if targetPlanet == '1:154:9':
    #     shipData = {
    #         'ship215': 100000,
    #         'ship219': 100,
    #         'ship228': 200
    #     }
    if int(targetPlanet[0]) > 4:
        attackPlanet = '4:2:8'
        attackPlanetId = 53
    if int(targetPlanet[0]) >= 7:
        attackPlanet = '9:399:12'
        attackPlanetId = 35
    if check:
        autoAddShip(attackPlanetId)
    if attack(attackPlanet, attackPlanetId, targetPlanet, shipData):
        attackIndex += 1
        # writeAttackIndex()
        # pass

# while True:
#     if needAttack(mainPlanetId):
#         autoAddShip(mainPlanetId)
#         autoAttack(mainPlanet, mainPlanetId)
#     time.sleep(10)
# while True:
#     if needAttack(53):
#         autoAddShip(53)
#         # autoAttack('4:2:8', 53)
#     time.sleep(10)
# while True:
#     if needAttack(53):
#         autoAddShip(53)
        # attack('4:2:8', 53, '7:77:7')
        # attack('4:2:8', 53, '8:11:7')
# attack(mainPlanet, mainPlanetId, '1:19:8', {
#     'ship215': 100000,
#     'ship219': 100
# })
# sys.exit(0)
# while True:
#     if needAttack(35):
#         autoAddShip(35)
        # attack('9:399:12', 35, '7:77:7')
        # attack('9:399:12', 35, '8:11:7')
        # autoAttack('9:399:12', 35)
    # time.sleep(10)
# attack(mainPlanet, mainPlanetId, '3:19:7', None, 8)
# attack(mainPlanet, mainPlanetId, '5:19:8', None, 8)
# attack('9:399:12', 35, '9:19:9')
# sys.exit(0)


planetMap2 = {
    '2:41:4': 52482,
    '2:41:6': 52483,
    '2:41:7': 52484,
    '2:41:8': 52485,
    '2:41:9': 52486,
    '2:41:11': 52487,
    '2:41:12': 52488,
}
# claim
# 1. 占领
# for i in range(4, 13):
#     claim(mainPlanet, mainPlanetId, '2:41:' + str(i))
# sys.exit(0)
# 1.1 获取ID
# getPlanetId(9)
# sys.exit(0)
# 2. 部署
# for planet in planetMap.keys():
#     sendShip(mainPlanet, planet, {
#         'ship219': 100
#     })
# sys.exit(0)
# 3. 检测
# for planet in planetMap2.keys():
#     checkResources(planet, planetMap2[planet])
# sys.exit(0)
# 升级建筑
# 34 研究院
# 22 23 24 仓库
# 81 资源模块
# 4. 升级资源
# for planet in planetMap2.keys():
#     upgradeBuilding(planet, 1, 1) # 挖矿
#     upgradeBuilding(planet, 4, 1) # 太阳能
#     upgradeBuilding(planet, 14, 5) # 机器人
#     upgradeBuilding(planet, 22, 15)
#     upgradeBuilding(planet, 23, 15)
#     upgradeBuilding(planet, 24, 15)
#     upgradeBuilding(planet, 81, 35) # 资源模块
# # sys.exit(0)
# # 5. 升级防御
# # for planet in planetMap2.keys():
#     upgradeBuilding(planet, 21, 15)
#     upgradeBuilding(planet, 44, 2)
#     upgradeBuilding(planet, 82, 15)
#     upgradeBuilding(planet, 83, 15)
#     checkDefend(planetMap[planet], 502, 916)
#     checkDefend(planetMap[planet], 402, 100000)
#     checkDefend(planetMap[planet], 401, 100000)
#     checkDefend(planetMap[planet], 403, 10000)
#     checkDefend(planetMap[planet], 404, 10000)
#     checkDefend(planetMap[planet], 406, 1000)
#     checkDefend(planetMap[planet], 438, 100)
#     # break
# sys.exit(0)


# 开新球
# newPlanet = '2:17:7'
# addNewPlanet(mainPlanet, mainPlanetId, newPlanet)
# upgradeBuilding(newPlanet, 1, 1)
# upgradeBuilding(newPlanet, 4, 1)
# upgradeBuilding(newPlanet, 14, 5)
# upgradeBuilding(newPlanet, 81, 40)

# 传送资源
# while True:
#     for planet in planetMap.keys():
#         transferResources(planet, mainPlanet)
# sys.exit(0)
# for planet in planetMap2.keys():
#     transferResources(mainPlanet, planet, {
#         'metal':20000000000,
#         'crystal':0,
#         'deuterium':0
#     })
# for i in range(6, 10):
#     transferResources(mainPlanet, '2:12:' + str(i), {
#         'metal':0,
#         'crystal':0,
#         'deuterium':10000000000
#     })
# sys.exit(0)

# transferResources(mainPlanet, '1:18:9')
# transferResources(mainPlanet, '1:18:6', {
#     'metal':2000000000,
#     'crystal':2000000000,
#     'deuterium':2000000000
# })

# for planet in planetMap.keys():
#     transferResources(mainPlanet, planet, {
#         'metal':0,
#         'crystal':0,
#         'deuterium':10000000000
#     })

# 发送舰队
# for planet in planetMap2.keys():
#     sendShip(mainPlanet, planet, {
#         'ship217': 20
#     })
# sys.exit(0)
#     sendShip(planet, mainPlanet, {
#         'ship216': 5*20,
#         'ship227': 11*20,
#         'ship219': 20*20
#     })

# 防御检测
# checkDefend(mainPlanetId, 404, 50000)
# for i in range(100):
#     checkDefend(mainPlanetId, 401, 1000000000000)
#     time.sleep(2)

# 核弹连发
# while True:
#     checkDefend(mainPlanetId, 502, 916)
#     time.sleep(1)
    # sendNuke('1:18:6', '1:19:8', 900)
    # time.sleep(1)
# sendNuke('1:18:6', '2:4:9', 10)


# autoAddShip(53)
# autoAddShip(35)
# autoAddShip(mainPlanetId)


# sys.exit(0)
# 连续探索
i = 0
j = 0
while True:
    try:
        i += 1
        if i > 2000: i = 1
        print(i)
        # 升建筑
        for planet in planetMap.keys():
            # pass
            upgradeBuilding(planet, 14, 5) # 机器人
            upgradeBuilding(planet, 15, 1) # 纳米机器人
            upgradeBuilding(planet, 33, 45) # 地形改造
            upgradeBuilding(planet, 1, 10) # 挖矿金属
            upgradeBuilding(planet, 2, 10) # 挖矿水晶
            upgradeBuilding(planet, 3, 10) # 挖矿重氢
            upgradeBuilding(planet, 4, 20) # 太阳能
            upgradeBuilding(planet, 21, 15) # 造船厂
            upgradeBuilding(planet, 22, 27) # 仓库
            upgradeBuilding(planet, 23, 27) # 仓库
            upgradeBuilding(planet, 24, 27) # 仓库
            upgradeBuilding(planet, 44, 3) # 导弹井
            upgradeBuilding(planet, 82, 1)
            upgradeBuilding(planet, 83, 1)
            upgradeBuilding(planet, 84, 1)
            upgradeBuilding(planet, 81, 60) # 资源模块
            checkDefend(planetMap[planet], 502, 916)
        
        # 造船
        for planet in planetMap.values():
            autoAddShip(planet)

        if needAttack(mainPlanetId):
            autoAddShip(mainPlanetId)
       
        # 搬运
        # if i % 3 == 1:
        # for l in range(14):
        #     planetList = [e for e in planetMap.keys()]
        #     transferResources(planetList[j % len(planetList)], mainPlanet)
        #     j += 1

        # 探险
        # for k in range(6):
        #     # explore(mainPlanet, mainPlanetId, {
        #     explore('9:399:12', 35, {
        #         'ship216': 5,
        #         'ship227': 11,
        #         'ship219': 20,
        #     }, 6)
    except Exception as e:
        print('异常了')
        import traceback
        traceback.print_exc()
    finally:
        print('sleep ... hours')
        time.sleep(60*1)
        # pass
